<template> 
    <div class="app-container">
        <el-card class="filter-container" shadow="never">
            <div>
                <i class="el-icon-search"></i>
                <span>筛选搜索</span>
                <el-button style="float: right" @click="handleSearchList()" type="primary" size="small">
                    查询结果
                </el-button>
                <el-button style="float: right;margin-right: 15px" @click="handleResetSearch()" size="small">
                    重置
                </el-button>
            </div>
            <div style="margin-top: 15px">
                <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
                    <el-form-item label="输入搜索：">
                        <el-input style="width: 203px" v-model="listQuery.param.title" placeholder="商品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类：">
                        <el-cascader clearable v-model="selectProductCateValue" :options="productCateOptions">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="上架状态：">
                        <el-select v-model="listQuery.param.status" placeholder="全部" clearable>
                            <el-option v-for="item in publishStatusOptions" :key="item.value" :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <el-card class="operate-container" shadow="never">
            <i class="el-icon-tickets"></i>
            <span>数据列表</span>
            <el-button class="btn-add" @click="handleAddProduct()" size="mini">
                添加
            </el-button>
        </el-card>
        <div class="table-container">
            <el-table ref="productTable" :data="list" style="width: 100%" @selection-change="handleSelectionChange"
                      v-loading="listLoading" border>
                <el-table-column type="selection" width="60" align="center"></el-table-column>
                <el-table-column label="编号" width="100" align="center">
                    <template slot-scope="scope">{{scope.row.id}}</template>
                </el-table-column>
                <el-table-column label="商品图片" width="120" align="center">
                    <template slot-scope="scope"><img style="height: 80px" :src="scope.row.listLogo"></template>
                </el-table-column>
                <el-table-column label="商品名称" align="center">
                    <template slot-scope="scope">
                        <p>{{scope.row.title}}</p>
                        <p>茶馆名：{{scope.row.teahouse.name}}</p>
                    </template>
                </el-table-column>
                <el-table-column label="分类" align="center" width="150px">
                    <template slot-scope="scope" v-if="scope.row.category != null">
                        {{scope.row.category.parentCategoryName}}->{{scope.row.category.name}}
                    </template>
                </el-table-column>
                <el-table-column label="价格/货号" width="120" align="center">
                    <template slot-scope="scope">
                        <p>价格：￥{{scope.row.price}}</p>
                    </template>
                </el-table-column>
                <el-table-column label="标签" width="140" align="center">
                    <template slot-scope="scope">
                        <p>上架：
                            <el-switch @change="handlePublishStatusChange(scope.$index, scope.row)" :active-value="1"
                                       :inactive-value="0" v-model="scope.row.status">
                            </el-switch>
                        </p>
                        <p>新品：
                            <el-switch @change="handleNewStatusChange(scope.$index, scope.row)" :active-value="1"
                                       :inactive-value="0"
                                       v-model="scope.row.newStatus">
                            </el-switch>
                        </p>
                        <p>推荐：
                            <el-switch @change="handleRecommendStatusChange(scope.$index, scope.row)" :active-value="1"
                                       :inactive-value="0" v-model="scope.row.recommandStatus">
                            </el-switch>
                        </p>
                    </template>
                </el-table-column>
                <el-table-column label="排序" width="100" align="center">
                    <template slot-scope="scope">{{scope.row.sort}}</template>
                </el-table-column>
                <el-table-column label="SKU库存" width="100" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit"
                                   @click="handleShowSkuEditDialog(scope.$index, scope.row)"
                                   circle></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="销量" width="100" align="center">
                    <template slot-scope="scope">{{scope.row.sale}}</template>
                </el-table-column>
                <el-table-column label="操作" width="160" align="center">
                    <el-table-column align="center">
                        <template slot-scope="scope">
                            <p>
                                <el-button size="mini" @click="handleUpdateProduct(scope.row)">编辑
                                </el-button>
                                <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
                                </el-button>
                                <el-button style="margin-top: 5px" size="mini" @click="addPrice(scope.row)">添加规格
                                </el-button>
                            </p>
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           layout="total, sizes,prev, pager, next,jumper" :page-size="listQuery.pageSize"
                           :page-sizes="[5,10,15]"
                           :current-page.sync="listQuery.pageNum" :total="total">
            </el-pagination>
        </div>
        <el-dialog title="编辑货品信息" :visible.sync="editSkuInfo.dialogVisible" width="60%">
            <el-table style="width: 100%;margin-top: 20px" :data="editSkuInfo.stockList" border>
                <el-table-column label="预览图" align="center" width="200px">
                    <template slot-scope="scope">
                        <el-upload
                                :class="scope.row.image.length>0?'hidden':''"
                                :headers="myHeaders"
                                :action="uploadsrc"
                                 accept="image/jpeg,image/gif,image/png"
                                list-type="picture-card"
                                :before-upload="handleBeforeUpload"
                                :on-success="function(res,file){return  uploadLogoSuccess(res,file,scope.$index)}"
                                :on-remove="handleRemove"
                                :on-error="uploadError"
                                :file-list="scope.row.image">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </template>
                </el-table-column>
                <el-table-column label="规格" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.specifications"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="库存" width="80" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.banlanceNumber"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="110" align="center">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.status" placeholder="请选择状态">
                            <el-option v-for="item in status" :key="item.id" :label="item.name"
                                       :value="item.id"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="价格" width="80" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.price"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="优惠价格" width="80" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.voucherPrice"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="快递费用" width="80" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.logisticsPrice"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="每单购买限制数量" width="80" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.limitPerOrder"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="开始售卖时间" align="center">
                    <template slot-scope="scope">
                        <el-date-picker
                                type="date"
                                placeholder="开始售卖时间"
                                v-model="scope.row.startTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                style="width: 100%;"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="结束售卖时间" align="center">
                    <template slot-scope="scope">
                        <el-date-picker
                                type="date"
                                placeholder="结束售卖时间"
                                v-model="scope.row.endTime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                style="width: 100%;"
                        ></el-date-picker>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
        <el-button @click="editSkuInfo.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSkuConfirm">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>
<script>
    const defaultListQuery = {
        pageNum: 1,
        pageSize: 10,
        param: {
            title: null,
            categoryId: null,
            status: null,
            verifyStatus: null
        }
    };
    export default {
        name: 'productList',
        data() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                editSkuInfo: {
                    dialogVisible: false,
                    stockList: [],
                    productAttr: []
                },
                status: [
                    {
                        id: 1,
                        name: '上架'
                    }, {
                        id: 0,
                        name: '下架'
                    }, {
                        id: 2,
                        name: '删除'
                    }
                ],
                operateType: null,
                listQuery: Object.assign({}, defaultListQuery),
                list: null,
                total: null,
                listLoading: true,
                selectProductCateValue: null,
                multipleSelection: [],
                productCateOptions: [],
                brandOptions: [],
                priceLists: [],

                publishStatusOptions: [{
                    value: 1,
                    label: '上架'
                }, {
                    value: 0,
                    label: '下架'
                }],
                verifyStatusOptions: [{
                    value: 1,
                    label: '审核通过'
                }, {
                    value: 0,
                    label: '未审核'
                }]
            };
        },
        created() {
            this.getList();
            this.getProductCateList();
        },
        watch: {
            selectProductCateValue: function(newValue) {
                if (newValue != null && newValue.length == 2) {
                    this.listQuery.param.categoryId = newValue[1];
                } else {
                    this.listQuery.param.categoryId = null;
                }

            }
        },
        filters: {
            verifyStatusFilter(value) {
                if (value === 1) {
                    return '审核通过';
                } else {
                    return '未审核';
                }
            }
        },
        methods: {
            uploadError(data) {
                this.$message.error(`上传失败，请重新上传`);
            },
            handleRemove(data) {
                this.editSkuInfo.stockList.previewImage = '';
            },
            uploadLogoSuccess(data, file, index) {
                console.log('res--data', data);
                console.log('file', file);
                console.log(this.editSkuInfo.stockList);
                if (data.returnCode == 200) {
                    if (this.editSkuInfo.stockList[index].previewImage == null) {
                        this.editSkuInfo.stockList[index].previewImage = [];
                    }
                    this.editSkuInfo.stockList[index].previewImage = data.data;
                    let data1 = {
                        url: data.data
                    };
                    let arr = [];
                    arr.push(data1);
                    this.imageUrl[index] = arr;
                } else {
                    this.$message.success(`上传失败，请重新上传`);
                }
            },
            getmyHeaders() {
                var dHeader = dynamicHeader();
                this.myHeaders.signature = dHeader.signature;
                this.myHeaders.nonce = dHeader.nonce;
                this.myHeaders.timestamp = dHeader.timestamp;
                this.myHeaders.appkey = dHeader.appkey;
                this.myHeaders.token = dHeader.token;
            },
            handleBeforeUpload(file) {
                this.getmyHeaders();
            },

            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            handleShowVerifyDetail(index, row) {
                console.log('handleShowVerifyDetail', row);
            },
            addPrice(row) {
                layer.open({
                    type: 2,
                    area: ['40%', '65%'],
                    title: '添加规格',
                    fixed: true, //不固定
                    maxmin: true,
                    content: ['/#/goodsPriceAdd?goodsId=' + row.id, 'yes']
                });
            },
            getProductSkuSp(row, index) {
                let spData = JSON.parse(row.spData);
                if (spData != null && goodsList < spData.length) {
                    return spData[goodsList].value;
                } else {
                    return null;
                }
            },
            getList() {
                this.listLoading = true;
                goodsList(this.listQuery).then(res => {
                    this.listLoading = false;
                    console.log(res);
                    this.list = res.data.list;
                    this.total = res.data.total;
                });
            },
            //没问题
            getProductCateList() {
                listWithChildren().then(res => {
                    let list = res.data;
                    this.productCateOptions = [];
                    for (let i = 0; i < list.length; i++) {
                        let children = [];
                        if (list[i].children != null && list[i].children.length > 0) {
                            for (let j = 0; j < list[i].children.length; j++) {
                                children.push({ label: list[i].children[j].name, value: list[i].children[j].id });
                            }
                        }
                        this.productCateOptions.push({ label: list[i].name, value: list[i].id, children: children });
                    }
                });
            },
            handleShowSkuEditDialog(index, row) {
                listPrice({
                    pageNum: 1, pageSize: 50, param: { goodsId: row.id }
                }).then(res => {
                    if (res.returnCode == 200) {
                        for (let i = 0; i < res.data.list.length; i++) {
                            let arr = [];
                            let data = {
                                url: res.data.list[i].previewImage
                            };
                            arr.push(data);
                            res.data.list[i].image = arr;
                        }
                        this.editSkuInfo.stockList = res.data.list;
                        this.editSkuInfo.dialogVisible = true;
                    } else if (res.returnCode == 10007) {
                        this.$message.error(`请添加价格`);
                    }
                });
            },

            handleEditSkuConfirm() {
                if (this.editSkuInfo.stockList == null || this.editSkuInfo.stockList.length <= 0) {
                    this.$message({
                        message: '暂无sku信息',
                        type: 'warning',
                        duration: 1000
                    });
                    return;
                }
                this.$confirm('是否要进行修改', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    updatePriceList(this.editSkuInfo.stockList).then(res => {
                        this.$message({
                            message: '修改成功',
                            type: 'success',
                            duration: 1000
                        });
                        this.editSkuInfo.dialogVisible = false;
                    });
                });
            },

            handleSearchList() {
                // this.listQuery.pageNum = 1;
                this.$set(this.listQuery, 'pageNum', 1);
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageNum = 1;
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            // 重置
            handleResetSearch() {
                this.selectProductCateValue = [];
                this.listQuery.param = Object.assign({}, defaultListQuery);
            },
            handleAddProduct() {
                layer.open({
                    type: 2,
                    area: ['60%', '85%'],
                    title: '增加商品',
                    fixed: true, //不固定
                    maxmin: true,
                    content: ['/#/goodsAdd', 'yes']
                });
            },
            handleUpdateProduct(row) {
                layer.open({
                    type: 2,
                    area: ['60%', '85%'],
                    title: '商品详情',
                    fixed: true, //不固定
                    maxmin: true,
                    content: ['/#/goodsUpdate?id=' + row.id + '&teahouseId=' + row.distributorId, 'yes']
                });
            },

            handlePublishStatusChange(index, row) {
                this.updatePublishStatus(row.status, row.id);
            },
            handleNewStatusChange(index, row) {
                this.updateNewStatus(row.newStatus, row.id);
            },
            handleRecommendStatusChange(index, row) {
                this.updateRecommendStatus(row.recommandStatus, row.id);
            },
            updatePublishStatus(status, id) {
                updateGoods({ status, id }).then(res => {
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 1000
                    });
                });
            },
            updateNewStatus(newStatus, id) {
                updateGoods({ newStatus, id }).then(res => {
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 1000
                    });
                });
            },
            updateRecommendStatus(recommendStatus, id) {
                updateGoods({ recommendStatus, id }).then(res => {
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 1000
                    });
                });
            },
            handleDelete(index, row) {
                this.$confirm('是否要进行删除操作?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = [];
                    ids.push(row.id);
                    let isDelete = 1;
                    this.updateDeleteStatus(isDelete, row.id);
                });
            },
            updateDeleteStatus(isDelete, id) {
                updateGoods({ isDelete, id }).then(res => {
                    this.$message({
                        message: '删除成功',
                        type: 'success',
                        duration: 1000
                    });
                });
                this.getList();
            }
        }
    };
</script>
<style>
    .specsdinput {
        width: 90% !important;
        height: auto;
        margin: 5px 5%;
    }

    .specsdinput input {
        margin: 0;
        text-align: center;
    }

    .hidden {
        height: 148px;
    }
</style>